/**
 * 微信小程序webpack配置
 * 支持ES6+语法、NPM模块等现代开发特性
 */

const path = require('path')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')

module.exports = {
  // 配置入口文件
  entry: {
    app: './app.js',
    // 自动查找pages下的所有页面入口
    ...getEntries('./pages'),
    // 自动查找components下的所有组件入口
    ...getEntries('./components'),
    // 自动查找src下的所有页面和组件入口
    ...getEntries('./src'),
  },
  
  // 配置输出目录
  output: {
    path: path.resolve(__dirname, '../dist'),
    filename: '[name].js',
  },
  
  // 配置模块解析规则
  resolve: {
    // 配置别名，简化导入路径
    alias: {
      '@': path.resolve(__dirname, '..'),
      '@utils': path.resolve(__dirname, '../utils'),
      '@services': path.resolve(__dirname, '../services'),
      '@components': path.resolve(__dirname, '../components'),
      '@assets': path.resolve(__dirname, '../assets'),
      '@pages': path.resolve(__dirname, '../pages'),
      '@config': path.resolve(__dirname, '../config'),
    },
    // 配置导入时可以省略的扩展名
    extensions: ['.js', '.json'],
  },
  
  // 配置模块处理规则
  module: {
    rules: [
      // 处理JS文件
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [
              ['@babel/preset-env', {
                targets: {
                  browsers: ['last 2 versions', 'safari >= 7']
                },
                useBuiltIns: 'usage',
                corejs: 3
              }]
            ],
            plugins: [
              '@babel/plugin-transform-runtime',
              '@babel/plugin-proposal-class-properties',
              '@babel/plugin-proposal-object-rest-spread'
            ]
          }
        }
      },
      // 处理JSON文件
      {
        test: /\.json$/,
        type: 'javascript/auto',
        loader: 'json-loader'
      },
      // 处理图片文件
      {
        test: /\.(png|jpg|gif|svg)$/,
        loader: 'file-loader',
        options: {
          name: '[name].[ext]',
          outputPath: 'images/',
        }
      },
    ]
  },
  
  // 配置插件
  plugins: [
    // 清理旧文件
    new CleanWebpackPlugin(),
    
    // 复制静态资源
    new CopyWebpackPlugin({
      patterns: [
        // 复制项目配置文件
        {
          from: '*.json',
          to: '[name][ext]',
          globOptions: {
            ignore: ['**/node_modules/**']
          }
        },
        // 复制页面配置文件
        {
          from: 'pages/**/*.json',
          to: '[path][name][ext]',
        },
        // 复制页面模板文件
        {
          from: 'pages/**/*.wxml',
          to: '[path][name][ext]',
        },
        // 复制页面样式文件
        {
          from: 'pages/**/*.wxss',
          to: '[path][name][ext]',
        },
        // 复制组件配置文件
        {
          from: 'components/**/*.json',
          to: '[path][name][ext]',
        },
        // 复制组件模板文件
        {
          from: 'components/**/*.wxml',
          to: '[path][name][ext]',
        },
        // 复制组件样式文件
        {
          from: 'components/**/*.wxss',
          to: '[path][name][ext]',
        },
        // 复制src下的配置文件
        {
          from: 'src/**/*.json',
          to: '[path][name][ext]',
        },
        // 复制src下的模板文件
        {
          from: 'src/**/*.wxml',
          to: '[path][name][ext]',
        },
        // 复制src下的样式文件
        {
          from: 'src/**/*.wxss',
          to: '[path][name][ext]',
        },
        // 复制应用样式文件
        {
          from: '*.wxss',
          to: '[name][ext]',
        },
        // 复制图片资源
        {
          from: 'images',
          to: 'images',
        },
        // 复制静态资源
        {
          from: 'assets',
          to: 'assets',
        },
      ],
    }),
  ],
  
  // 配置优化选项
  optimization: {
    // 代码分离
    splitChunks: {
      chunks: 'all',
      name: 'common',
      minSize: 0,
      maxInitialRequests: Infinity,
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendor',
          priority: -10,
        },
        default: {
          minChunks: 2,
          priority: -20,
          reuseExistingChunk: true
        }
      }
    },
  },
  
  // 不打包微信小程序内置API
  externals: {
    'wx': 'commonjs wx'
  },
  
  // 输出详细的构建信息
  stats: {
    modules: false,
    chunks: false,
    children: false,
    timings: true
  },
  
  // 配置开发服务器
  devServer: {
    contentBase: path.join(__dirname, '../dist'),
    compress: true,
    port: 9000
  }
};

/**
 * 获取指定目录下的所有入口文件
 * @param {string} dir - 目录路径
 * @returns {Object} 入口配置对象
 */
function getEntries(dir) {
  const fs = require('fs')
  const path = require('path')
  const entries = {}
  
  // 检查目录是否存在
  if (!fs.existsSync(path.resolve(__dirname, '..', dir))) {
    return entries
  }
  
  // 递归查找所有JS文件
  function findEntries(directory, base) {
    const files = fs.readdirSync(path.resolve(__dirname, '..', directory))
    
    files.forEach(file => {
      const fullPath = path.join(directory, file)
      const stats = fs.statSync(path.resolve(__dirname, '..', fullPath))
      
      if (stats.isDirectory()) {
        findEntries(fullPath, base)
      } else if (file.endsWith('.js') && !file.includes('.config.js')) {
        // 排除配置文件
        const relativePath = path.relative(base, fullPath)
        const entryName = relativePath.replace('.js', '')
        entries[entryName] = './' + fullPath
      }
    })
  }
  
  findEntries(dir, dir)
  return entries
} 